var url = require('url');
var http = require('http');
var iconv = require('iconv-lite')
var webInterface = require('./webInterface');
var log4js = require('log4js');
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file('logs/queryAfterSales.log'), 'queryAfterSales');
var logger = log4js.getLogger('queryAfterSales');

var mdskipApi =  'http://mdskip.taobao.com/extension/query_after_sales.do?';
var tbskipApi = 'http://tbskip.taobao.com/json/query_after_sales.do?';
var tbskipurl = 'http://tbskip.daily.taobao.net/json/query_after_sales.do?_ksTS=1362724580245_645&callback=jsonp646&seller_id=2015076156&auction_id=1603999792&aftersale_id=7795';
var aftersalesCallback = function(jsonObj){
	return jsonObj;
}

exports.mdskipApi = mdskipApi;
exports.tbskipApi = tbskipApi;

exports.verify = function (tbskipurl, callback){
	var mdskipurl = convertToMdskipUrl(tbskipurl);
	tbskipurl = prepareTbskipUrl(tbskipurl);
	logger.error('readUrl:	' + tbskipurl);
	webInterface.sendRequest(mdskipurl, tbskipurl, function(mdskipres, tbskipres){
		try{
			var tbskipResult = eval(tbskipres);
			var mdskipResult = eval(mdskipres);
			if(!tbskipResult.success || !mdskipResult.success){
				logger.error("NotSuccess	" + mdskipurl + "		" + tbskipurl);
				return;
			}
			
			if(tbskipResult.content != mdskipResult.content){
				logger.error("NotEqual	" + mdskipurl + "		" + tbskipurl);
				return;
			}
			logger.error('equals');
		} catch (e) {
			logger.error("Exception:" + mdskipMealUrl + "	" + tbskipMealUrl, e);
		}
		
		if((typeof callback != 'undefined') && callback != null){
			callback();
		}
	});
}


function convertToMdskipUrl(tbskipurl){
	var tbskipRequest = url.parse(tbskipurl);
	var params = parseQueryString(tbskipRequest.query);
	var mdskipurl = mdskipApi;
	for(var key in params){
		if(key != 'callback'){
			var value = params[key];
			mdskipurl += key + "=" + value + "&";
		}
	}
	mdskipurl += "callback=aftersalesCallback&debug=true";
	return mdskipurl;
}

function prepareTbskipUrl(tbskipurl){
	var result = tbskipApi;
	var tbskipRequest = url.parse(tbskipurl);
	var params = parseQueryString(tbskipRequest.query);
	for(var key in params){
		if(key != 'callback'){
			var value = params[key];
			result += key + "=" + value + "&";
		}
	}
	result += 'callback=aftersalesCallback'
	return result;
}



function parseQueryString(queryString){
	var params = {};

	var paramPv = queryString.split('&');
	for(var i=0; i < paramPv.length; i++){
		var pvString = paramPv[i];
		var pvPair = pvString.split('=');
		params[pvPair[0]] = pvPair[1];
	}
	return params;
}
